package com.ruicar.afs.jobadmin.service.impl;

import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.job.core.enums.ExecutorBlockStrategyEnum;
import com.ruicar.afs.cloud.common.job.core.glue.GlueTypeEnum;
import com.ruicar.afs.cloud.common.job.core.util.DateUtil;
import com.ruicar.afs.jobadmin.mapper.*;
import com.ruicar.afs.jobadmin.core.cron.CronExpression;
import com.ruicar.afs.jobadmin.core.model.AfsJobGroup;
import com.ruicar.afs.jobadmin.core.model.AfsJobInfo;
import com.ruicar.afs.jobadmin.core.model.AfsJobLogReport;
import com.ruicar.afs.jobadmin.core.route.ExecutorRouteStrategyEnum;
import com.ruicar.afs.jobadmin.core.thread.JobScheduleHelper;
import com.ruicar.afs.jobadmin.core.util.I18nUtil;
import com.ruicar.afs.jobadmin.service.AfsJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.*;

/**
 * The type AfsJobServiceImpl
 * <p>Description: </p>
 *
 * @author Fzero
 * @version 1.0
 * @date Created on 2020.06.13 14:17:12
 * @since 1.0
 */
@Service
public class AfsJobServiceImpl implements AfsJobService {
    /**
     * Logger
     * <p>Description: </p>
     */
    private static Logger logger = LoggerFactory.getLogger(AfsJobServiceImpl.class);

    /**
     * Afs job group mapper
     * <p>Description: </p>
     */
    @Resource
    private AfsJobGroupMapper afsJobGroupMapper;
    /**
     * Afs job info mapper
     * <p>Description: </p>
     */
    @Resource
    private AfsJobInfoMapper afsJobInfoMapper;
    /**
     * Afs job log mapper
     * <p>Description: </p>
     */
    @Resource
    public AfsJobLogMapper afsJobLogMapper;
    /**
     * Afs job log glue mapper
     * <p>Description: </p>
     */
    @Resource
    private AfsJobLogGlueMapper afsJobLogGlueMapper;
    /**
     * Afs job log report mapper
     * <p>Description: </p>
     */
    @Resource
    private AfsJobLogReportMapper afsJobLogReportMapper;

    /**
     * Add response
     *
     * @param jobInfo job info
     * @return the response
     */
    @Override
    public IResponse<String> add(AfsJobInfo jobInfo) {
        // valid
        AfsJobGroup group = afsJobGroupMapper.load(jobInfo.getJobGroup());
        if (group == null) {
            return IResponse.fail(I18nUtil.getString("system_please_choose") + I18nUtil.getString("jobinfo_field_jobgroup"));
        }
        if (!CronExpression.isValidExpression(jobInfo.getJobCron())) {
            return IResponse.fail(I18nUtil.getString("jobinfo_field_cron_unvalid"));
        }
        if (jobInfo.getJobDesc() == null || jobInfo.getJobDesc().trim().length() == 0) {
            return IResponse.fail(I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_jobdesc"));
        }
        if (jobInfo.getAuthor() == null || jobInfo.getAuthor().trim().length() == 0) {
            return IResponse.fail(I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_author"));
        }
        if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
            return IResponse.fail(I18nUtil.getString("jobinfo_field_executorRouteStrategy") + I18nUtil.getString("system_unvalid"));
        }
        if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
            return IResponse.fail(I18nUtil.getString("jobinfo_field_executorBlockStrategy") + I18nUtil.getString("system_unvalid"));
        }
        if (GlueTypeEnum.match(jobInfo.getGlueType()) == null) {
            return IResponse.fail(I18nUtil.getString("jobinfo_field_gluetype") + I18nUtil.getString("system_unvalid"));
        }
        if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType()) && (jobInfo.getExecutorHandler() == null || jobInfo.getExecutorHandler().trim().length() == 0)) {
            return IResponse.fail((I18nUtil.getString("system_please_input") + "JobHandler"));
        }

        // fix "\r" in shell
        if (GlueTypeEnum.GLUE_SHELL == GlueTypeEnum.match(jobInfo.getGlueType()) && jobInfo.getGlueSource() != null) {
            jobInfo.setGlueSource(jobInfo.getGlueSource().replaceAll("\r", ""));
        }

        // ChildJobId valid
        if (jobInfo.getChildJobId() != null && jobInfo.getChildJobId().trim().length() > 0) {
            String[] childJobIds = jobInfo.getChildJobId().split(",");
            for (String childJobIdItem : childJobIds) {
                if (childJobIdItem != null && childJobIdItem.trim().length() > 0 && isNumeric(childJobIdItem)) {
                    AfsJobInfo childJobInfo = afsJobInfoMapper.loadById(Integer.parseInt(childJobIdItem));
                    if (childJobInfo == null) {
                        return IResponse.fail(MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_not_found")), childJobIdItem));
                    }
                } else {
                    return IResponse.fail(MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_unvalid")), childJobIdItem));
                }
            }

            // join , avoid "xxx,,"
            String temp = "";
            for (String item : childJobIds) {
                temp += item + ",";
            }
            temp = temp.substring(0, temp.length() - 1);

            jobInfo.setChildJobId(temp);
        }

        // add in db
        jobInfo.setAddTime(new Date());
        jobInfo.setUpdateTime(new Date());
        jobInfo.setGlueUpdatetime(new Date());
        afsJobInfoMapper.save(jobInfo);
        if (jobInfo.getId() < 1) {
            return IResponse.fail( (I18nUtil.getString("jobinfo_field_add") + I18nUtil.getString("system_fail")));
        }

        return IResponse.success(String.valueOf(jobInfo.getId()));
    }

    /**
     * Is numeric boolean
     *
     * @param str str
     * @return the boolean
     */
    private boolean isNumeric(String str) {
        try {
            int result = Integer.valueOf(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * Update response
     *
     * @param jobInfo job info
     * @return the response
     */
    @Override
    public IResponse<String> update(AfsJobInfo jobInfo) {

        // valid
        if (!CronExpression.isValidExpression(jobInfo.getJobCron())) {
            return IResponse.fail(I18nUtil.getString("jobinfo_field_cron_unvalid"));
        }
        if (jobInfo.getJobDesc() == null || jobInfo.getJobDesc().trim().length() == 0) {
            return IResponse.fail( (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_jobdesc")));
        }
        if (jobInfo.getAuthor() == null || jobInfo.getAuthor().trim().length() == 0) {
            return IResponse.fail( (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_author")));
        }
        if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
            return IResponse.fail( (I18nUtil.getString("jobinfo_field_executorRouteStrategy") + I18nUtil.getString("system_unvalid")));
        }
        if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
            return IResponse.fail( (I18nUtil.getString("jobinfo_field_executorBlockStrategy") + I18nUtil.getString("system_unvalid")));
        }

        // ChildJobId valid
        if (jobInfo.getChildJobId() != null && jobInfo.getChildJobId().trim().length() > 0) {
            String[] childJobIds = jobInfo.getChildJobId().split(",");
            for (String childJobIdItem : childJobIds) {
                if (childJobIdItem != null && childJobIdItem.trim().length() > 0 && isNumeric(childJobIdItem)) {
                    AfsJobInfo childJobInfo = afsJobInfoMapper.loadById(Integer.parseInt(childJobIdItem));
                    if (childJobInfo == null) {
                        return IResponse.fail(MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_not_found")), childJobIdItem));
                    }
                } else {
                    return IResponse.fail(MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_unvalid")), childJobIdItem));
                }
            }

            // join , avoid "xxx,,"
            String temp = "";
            for (String item : childJobIds) {
                temp += item + ",";
            }
            temp = temp.substring(0, temp.length() - 1);

            jobInfo.setChildJobId(temp);
        }

        // group valid
        AfsJobGroup jobGroup = afsJobGroupMapper.load(jobInfo.getJobGroup());
        if (jobGroup == null) {
            return IResponse.fail( (I18nUtil.getString("jobinfo_field_jobgroup") + I18nUtil.getString("system_unvalid")));
        }

        // stage job info
        AfsJobInfo exists_jobInfo = afsJobInfoMapper.loadById(jobInfo.getId());
        if (exists_jobInfo == null) {
            return IResponse.fail( (I18nUtil.getString("jobinfo_field_id") + I18nUtil.getString("system_not_found")));
        }

        // next trigger time (5s后生效，避开预读周期)
        long nextTriggerTime = exists_jobInfo.getTriggerNextTime();
        if (exists_jobInfo.getTriggerStatus() == 1 && !jobInfo.getJobCron().equals(exists_jobInfo.getJobCron())) {
            try {
                Date nextValidTime = new CronExpression(jobInfo.getJobCron()).getNextValidTimeAfter(new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));
                if (nextValidTime == null) {
                    return IResponse.fail( I18nUtil.getString("jobinfo_field_cron_never_fire"));
                }
                nextTriggerTime = nextValidTime.getTime();
            } catch (ParseException e) {
                logger.error(e.getMessage(), e);
                return IResponse.fail( I18nUtil.getString("jobinfo_field_cron_unvalid") + " | " + e.getMessage());
            }
        }

        exists_jobInfo.setJobGroup(jobInfo.getJobGroup());
        exists_jobInfo.setJobCron(jobInfo.getJobCron());
        exists_jobInfo.setJobDesc(jobInfo.getJobDesc());
        exists_jobInfo.setAuthor(jobInfo.getAuthor());
        exists_jobInfo.setAlarmEmail(jobInfo.getAlarmEmail());
        exists_jobInfo.setExecutorRouteStrategy(jobInfo.getExecutorRouteStrategy());
        exists_jobInfo.setExecutorHandler(jobInfo.getExecutorHandler());
        exists_jobInfo.setExecutorParam(jobInfo.getExecutorParam());
        exists_jobInfo.setExecutorBlockStrategy(jobInfo.getExecutorBlockStrategy());
        exists_jobInfo.setExecutorTimeout(jobInfo.getExecutorTimeout());
        exists_jobInfo.setExecutorFailRetryCount(jobInfo.getExecutorFailRetryCount());
        exists_jobInfo.setChildJobId(jobInfo.getChildJobId());
        exists_jobInfo.setTriggerNextTime(nextTriggerTime);

        exists_jobInfo.setUpdateTime(new Date());
        afsJobInfoMapper.update(exists_jobInfo);


        return IResponse.success("");
    }

    /**
     * Remove response
     *
     * @param id id
     * @return the response
     */
    @Override
    public IResponse<Boolean> remove(int id) {
        AfsJobInfo afsJobInfo = afsJobInfoMapper.loadById(id);
        if (afsJobInfo == null) {
            return IResponse.success(Boolean.TRUE);
        }

        afsJobInfoMapper.delete(id);
        afsJobLogMapper.delete(id);
        afsJobLogGlueMapper.deleteByJobId(id);
        return IResponse.success(Boolean.TRUE);
    }

    /**
     * Start response
     *
     * @param id id
     * @return the response
     */
    @Override
    public IResponse<String> start(int id) {
        AfsJobInfo afsJobInfo = afsJobInfoMapper.loadById(id);

        // next trigger time (5s后生效，避开预读周期)
        long nextTriggerTime = 0;
        try {
            Date nextValidTime = new CronExpression(afsJobInfo.getJobCron()).getNextValidTimeAfter(new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));
            if (nextValidTime == null) {
                return IResponse.fail(I18nUtil.getString("jobinfo_field_cron_never_fire"));
            }
            nextTriggerTime = nextValidTime.getTime();
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
            return IResponse.fail(I18nUtil.getString("jobinfo_field_cron_unvalid") + " | " + e.getMessage());
        }

        afsJobInfo.setTriggerStatus(1);
        afsJobInfo.setTriggerLastTime(0);
        afsJobInfo.setTriggerNextTime(nextTriggerTime);

        afsJobInfo.setUpdateTime(new Date());
        afsJobInfoMapper.update(afsJobInfo);
        return IResponse.success("");
    }

    /**
     * Stop response
     *
     * @param id id
     * @return the response
     */
    @Override
    public IResponse<String> stop(int id) {
        AfsJobInfo afsJobInfo = afsJobInfoMapper.loadById(id);

        afsJobInfo.setTriggerStatus(0);
        afsJobInfo.setTriggerLastTime(0);
        afsJobInfo.setTriggerNextTime(0);

        afsJobInfo.setUpdateTime(new Date());
        afsJobInfoMapper.update(afsJobInfo);
        return IResponse.success("");
    }

    /**
     * Chart info map
     *
     * @param startDate start date
     * @param endDate   end date
     * @return the map
     */
    @Override
    public Map<String, Object> chartInfo(Date startDate, Date endDate) {

        // process
        List<String> triggerDayList = new ArrayList<String>();
        List<Integer> triggerDayCountRunningList = new ArrayList<Integer>();
        List<Integer> triggerDayCountSucList = new ArrayList<Integer>();
        List<Integer> triggerDayCountFailList = new ArrayList<Integer>();
        int triggerCountRunningTotal = 0;
        int triggerCountSucTotal = 0;
        int triggerCountFailTotal = 0;

        List<AfsJobLogReport> logReportList = afsJobLogReportMapper.queryLogReport(startDate, endDate);

        if (logReportList != null && logReportList.size() > 0) {
            for (AfsJobLogReport item : logReportList) {
                String day = DateUtil.formatDate(item.getTriggerDay());
                int triggerDayCountRunning = item.getRunningCount();
                int triggerDayCountSuc = item.getSucCount();
                int triggerDayCountFail = item.getFailCount();

                triggerDayList.add(day);
                triggerDayCountRunningList.add(triggerDayCountRunning);
                triggerDayCountSucList.add(triggerDayCountSuc);
                triggerDayCountFailList.add(triggerDayCountFail);

                triggerCountRunningTotal += triggerDayCountRunning;
                triggerCountSucTotal += triggerDayCountSuc;
                triggerCountFailTotal += triggerDayCountFail;
            }
        } else {
            for (int i = -6; i <= 0; i++) {
                triggerDayList.add(DateUtil.formatDate(DateUtil.addDays(new Date(), i)));
                triggerDayCountRunningList.add(0);
                triggerDayCountSucList.add(0);
                triggerDayCountFailList.add(0);
            }
        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("triggerDayList", triggerDayList);
        result.put("triggerDayCountRunningList", triggerDayCountRunningList);
        result.put("triggerDayCountSucList", triggerDayCountSucList);
        result.put("triggerDayCountFailList", triggerDayCountFailList);

        result.put("triggerCountRunningTotal", triggerCountRunningTotal);
        result.put("triggerCountSucTotal", triggerCountSucTotal);
        result.put("triggerCountFailTotal", triggerCountFailTotal);


        int jobInfoCount = afsJobInfoMapper.findAllCount();
        int jobLogCount = 0;
        int jobLogSuccessCount = 0;
        AfsJobLogReport afsJobLogReport = afsJobLogReportMapper.queryLogReportTotal();
        if (afsJobLogReport != null) {
            jobLogCount = afsJobLogReport.getRunningCount() + afsJobLogReport.getSucCount() + afsJobLogReport.getFailCount();
            jobLogSuccessCount = afsJobLogReport.getSucCount();
        }

        // executor count
        Set<String> executorAddressSet = new HashSet<String>();
        List<AfsJobGroup> groupList = afsJobGroupMapper.findAll();

        if (groupList != null && !groupList.isEmpty()) {
            for (AfsJobGroup group : groupList) {
                if (group.getRegistryList() != null && !group.getRegistryList().isEmpty()) {
                    executorAddressSet.addAll(group.getRegistryList());
                }
            }
        }

        int executorCount = executorAddressSet.size();
        result.put("jobInfoCount", jobInfoCount);
        result.put("jobLogCount", jobLogCount);
        result.put("jobLogSuccessCount", jobLogSuccessCount);
        result.put("executorCount", executorCount);
        return result;
    }

}
